package top.yangbuyi.utils;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description: 杨不易网站:www.yangbuyi.top
 * @program: yangbuyiopenHis2020
 * @ClassName: IdGeneratorSnowflake
 * @create: 2020-08-27 21:15
 * @author: yangbuyi
 * @since： JDK1.8
 * @IdGeneratorSnowflake: 雪花算法工具类$分布式生成ID
 * workId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
 **/
public class IdGeneratorSnowflake {
	  private static final Logger log = LoggerFactory.getLogger(IdGeneratorSnowflake.class);
	  private static long workId = 0;
	  private static long datacenterId = 1;
	  private static Snowflake snowflake;

	  static {
			try {
				  workId = RandomUtil.randomLong(31);
				  log.info("当前机器的工作ID为:" + workId);
				  snowflake = IdUtil.createSnowflake(workId, datacenterId);
				  log.info("snowflake" + snowflake);
			} catch (Exception e) {
				  e.printStackTrace();
				  log.error("当前机器的workId获取失败", e);
				  workId = NetUtil.getLocalhostStr().hashCode();
			}
	  }

	  /**
	   * 生成ID
	   */
	  public static synchronized Long snowflakeId() {
			log.info("snowFlake:" + snowflake);
			return snowflake.nextId();
	  }

	  /**
	   * 根据前缀前成ID
	   */
	  public static String generatorIdWithProfix(String profix) {
			return profix + snowflakeId();
	  }

	  public static void main(String[] args) {
			for (int i = 0; i < 10; i++) {
				  Long aLong = IdGeneratorSnowflake.snowflakeId();
				  System.out.println(aLong);
			}
	  }
}

